param ([string] $Path, [string] $NewFolderName)

function New-Folder( [string] $Path, [string] $FolderName)
{
    $ParentFolderItem = [DataWorks.MI.Core.Item]::GetInstance($Path)
    $ValueBag = New-Object -TypeName "DataWorks.MI.Core.Collections.NamedValueBag"
    [DataWorks.MI.Core.IProperty] $ChildrenProperty = $ParentFolderItem.Properties["Children"]
    [DataWorks.MI.Core.IItem] $NewFolderItem = [DataWorks.MI.Core.Item]::CreateInstance("Core.Folder", $FolderName, $ValueBag, $ChildrenProperty)
        
    return $NewFolderItem
}

# Append new Foldername to create new FQN (Fully qualified name)
$TargetFolderFQN = [DataWorks.MI.Core.Namespace.FQN]::AppendNamePart($Path , $NewFolderName)
    
# Query the new FQN and see whether this folder already exists
[DataWorks.MI.Core.Namespace.IItemNsElementInfo] $ElementInfo = [DataWorks.MI.Core.Namespace.NamespaceProvider]::Instance.ResolveFQN($TargetFolderFQN)
    
# If folder item doesn't exist create new one
if ( $ElementInfo -eq $null)
{
    $NewFolderItem = New-Folder -Path $Path -FolderName $NewFolderName 
    return $NewFolderItem
}
else
{
    if ( $ElementInfo.ItemType.IsA("Core.Folder"))
    {
        $TargetFolderItem = $ElementInfo.Item
        return $TargetFolderItem
    }
        else
        {
            throw "Specified FQN exists already, but is not a folder!"
        }
}












